import axios from 'axios'
import ala from '@/service/ala'
const apiBaseUrl = 'https://diyapi.5ug.com/'
// const apiBaseUrl = 'http://localhost:6800/'


export async function diyHttpGet(apiUrl, data) {
  var request
  await axios.get(apiBaseUrl + apiUrl, {
    params: data,
    headers: ala.header(apiUrl, true)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    if (error.response && error.response.data) {
      ala.error(error.response.data.message)
    }
  })
  var response = result(request, apiUrl)
  return response
}

export async function diyHttpPost(apiUrl, data) {
  var request
  await axios.post(apiBaseUrl + apiUrl, data, {
    headers: ala.header(apiUrl, true)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    if (error.response && error.response.data) {
      ala.error(error.response.data.message)
    }
  })
  var response = result(request, apiUrl)
  return response
}
//  Put方法：改
export async function diyHttpPut(apiUrl, data) {
  var request
  await axios.put(apiBaseUrl + apiUrl, data, {
    headers: ala.header(apiUrl, true)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    if (error.response && error.response.data) {
      ala.error(error.response.data.message)
    }
  })
  var response = result(request, apiUrl)
  return response
}
export async function diyHttpDelete(apiUrl, data) {
  var para = parseParams(data)
  var request
  if (para) {
    apiUrl += '?' + para
  }
  var result
  await axios.delete(apiBaseUrl + apiUrl, {
    paras: data,
    headers: ala.header(apiUrl, true)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    if (error.response && error.response.data) {
      ala.error(error.response.data.message)
    }
  })
  return result
}

function parseParams(data) {
  try {
    var tempArr = []
    for (var i in data) {
      var key = encodeURIComponent(i)
      var value = encodeURIComponent(data[i])
      tempArr.push(key + '=' + value)
    }
    var urlParamsStr = tempArr.join('&')
    return urlParamsStr
  } catch (err) {
    return ''
  }
}

function result(response, apiUrl) {
  if (response && response.status === 200) {
    if (response.data.status === 1) {
      if (response.data.result) {
        return response.data.result
      } else {
        return response.data
      }
    } else {
      ala.error(response.data.message)
      return null
    }
  }
  if (response && response.status === 400) {
    ala.error('404错误：' + apiBaseUrl + apiUrl)
  }
}